package org.apache.servicecomb.samples.practise.houserush.sale.aggregate;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Snake Man
 * @system:
 * @DateTime: 2022/1/18 12:59
 * @Description:
 */
@Data
@Entity
@Table(name = "sales")
@SQLDelete(sql = "update sales set deleted_at = now() where id = ?")
@Where(clause = "deleted_at is null")
@EntityListeners(AuditingEntityListener.class)
public class Sale {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String state = "new";

    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    private Date beginAt;

    @Temporal(TemporalType.TIMESTAMP)
    private Date endAt;

    @OneToMany(mappedBy = "sale")
    @Fetch(FetchMode.JOIN)
    @JsonIgnoreProperties(ignoreUnknown = true, value = {"sale"})
    private List<HouseOrder> houseOrders = new ArrayList<>();

    private Integer realestateId;

    //活动名称
    @Transient
    private String realestateName;

    @Temporal(TemporalType.TIMESTAMP)
    private Date deletedAt;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;

    //活动状态
    //1.published 活动发布成功
    //2.opening 活动开售中
    //3.finished 活动售罄/发售结束
    public String getState() {
        //获取当前时间
        Date now = new Date();
        //判断当前时间是否小于活动开始时间(开售时间)
        if (now.getTime() < beginAt.getTime()) {
            //活动未开始，返回活动发布成功
            return "published";
        } else if (now.getTime() > beginAt.getTime() && now.getTime() < endAt.getTime()) {
            //如果当前时间大于活动开始时间，并且，当前时间小于活动结束时间，返回opening
            return "opening";
        } else {
            //如果以上两种情况都不符合，那就是活动结束，活动房源已售罄，返回finished
            return "finished";

        }
    }

}
